<?php
/**
 * Initiiert das MVC Pattern
 *
 */
/*
 * Includes
 * @see Kanedo_Front_Controller_Exception
 */
require_once 'Kanedo/Front/Controller/Exception.php';

class Kanedo_Front_Controller
{
	protected static $_instance = null;
	
	protected $_public = true;
	/**
	 * Request Object
	 *
	 * @var Kanedo_Router_Request
	 */
	protected $_request = null;
	

	/**
	 * Controller Object
	 *
	 * @var Kanedo_Controller_Abstract
	 */
	protected $_controller = null;
	
	protected $_pathToGroup = null;
	private function __construct()
	{
		
	}
	
	/**
	 * Statische Funktoin zum holen der Instance; Singletone pattern
	 *
	 * @access public
	 * @static 
	 * @return Kanedo_Front_Controller
	 */
	public static function getInstance()
	{
		if (self::$_instance === null)
		{
			self::$_instance = new Kanedo_Front_Controller();
		}
		return self::$_instance;
	}
	
	protected function adminPublicRoute($request)
	{
		if($request->getGroup() != "admin")
		{
			$request->setGroup('public');
			$request->setController('index');
			$request->setAction('index');
		}
		return $request;
	}
	
	public function setRequest (Kanedo_Router_Request $request)
	{
		$this->_request = $this->adminPublicRoute(&$request);
	}
	
	public function initGroup()
	{
		$this->_pathToGroup = "/application/".$this->_request->getGroup()."/";
	}
	public function initController()
	{
		if ($this->_pathToGroup !== null)
		{
			require_once "../".$this->_pathToGroup."Controller/".$this->_request->getController()."Controller.php";
		}
		
		if (class_exists($this->_request->getController()."Controller"))
		{
			$controller = $this->_request->getController()."Controller";
			$this->_controller = new $controller($this->_request);
		}else {
			throw new Kanedo_Front_Controller_Exception("no_controller", 404);
		}
	}
	public function initAction()
	{
		if($this->_controller == null) {
			throw new Kanedo_Front_Controller_Exception("no_controller", 404);
		}
		$this->_controller->init();
		$this->_controller->preDispatch();
		$action = $this->_request->getAction()."Action";
		$this->_controller->$action();
		$this->_controller->postDispatch();
		$this->_controller->flush();
	}
}
?>